/*
 * @Description: Modbus RTU Master
 * @Author: Dryad
 * @Date: 2019-09-12 14:35:43
 * @LastEditors: Dryad
 * @LastEditTime: 2019-09-15 20:44:08
 * @Encoding: utf-8
 */
#pragma once
#if __cplusplus
extern "C"
{
#endif

	typedef enum
	{
		Modbus_Master_OK,		   /* 正常 */
		Modbus_Master_Busy,		   /* 总线忙 */
		Modbus_Master_NoRespond,   /* 无应答 */
		Modbus_Master_Frame_Error, /* 帧错误 */
	} Modbus_Error_Code;

	/* 初始化Modbus RTU Master */
	void MR_Master_Init(unsigned long baudrate);

	/* 读保持寄存器数据，功能码0x03 */
	Modbus_Error_Code MR_Read_Holding_Registers(const unsigned char slave_addr,			  /* 从机地址 */
												const unsigned short start_register_addr, /* 寄存器起始地址 */
												const unsigned short register_num,		  /* 寄存器数量 */
												unsigned short *data,					  /* 读取值写入地址 */
												const long mutex_timeout				  /* 等待总线空闲时间 */
	);

	/* 写单个保持寄存器，功能码0x06 */
	Modbus_Error_Code MR_Writer_Holding_Register(const unsigned char slave_addr,	 /* 从机地址 */
												 const unsigned short register_addr, /* 寄存器地址 */
												 const unsigned short data,			 /* 待写入值 */
												 const long mutex_timeout			 /* 等待总线空闲时间 */
	);

	/* 写多个保持寄存器，功能码0x10 */
	Modbus_Error_Code MR_Write_Multiple_Holding_Registers(const unsigned char slave_addr,			/* 从机地址 */
														  const unsigned short start_register_addr, /* 寄存器起始地址 */
														  const unsigned short register_num,		/* 寄存器数量 */
														  const unsigned short *data,				/* 待写入值地址 */
														  const long mutex_timeout					/* 等待总线空闲时间 */
	);

	/* 读线圈，功能码0x01 */
	Modbus_Error_Code MR_Read_Coils(const unsigned char slave_addr,		  /* 从机地址 */
									const unsigned short start_coil_addr, /* 线圈起始地址 */
									const unsigned short coil_num,		  /* 线圈数量 */
									unsigned char *data,				  /* 读取值写入地址 */
									const long mutex_timeout			  /* 等待总线空闲时间 */
	);

	/* 写单线圈，功能码0x05 */
	Modbus_Error_Code MR_Write_Coil(const unsigned char slave_addr, /* 从机地址 */
									const unsigned short coil_addr, /* 线圈地址 */
									const unsigned char coil_data,  /* 线圈值，0x00为OFF,否则为ON */
									const long mutex_timeout		/* 等待总线空闲时间 */
	);

	/* 写多线圈，功能码0x0F */
	Modbus_Error_Code MR_Write_Multiple_Coils(const unsigned char slave_addr,		/* 从机地址 */
											  const unsigned short start_coil_addr, /* 线圈起始地址 */
											  const unsigned short coil_num,		/* 线圈数量 */
											  const unsigned char *data,			/* 待写入值地址 */
											  const long mutex_timeout				/* 等待总线空闲时间 */
	);

#ifdef __cplusplus
}
#endif // __cplusplus
